package com.zhengzengliang.jwt.controller;

import com.zhengzengliang.jwt.result.ResultObject;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
public class LoginRedisController {

    private String key = "TOKEN:USER:";

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @PostMapping("/app/redis/login")
    public ResultObject login(String name, String pwd, HttpServletRequest request){
        ResultObject ro = new ResultObject();
        if( name.equals("lisi") && "123".equals(pwd)){
            //登录成功
            String token = UUID.randomUUID().toString().replaceAll("-","").toUpperCase();
            String referer = request.getHeader("Referer");
            Map<String,String> map = new HashMap<>();
            map.put("userId","1001");
            map.put("name",name);
            map.put("role","admin");
            map.put("ref",referer);
            System.out.println("LoginRedisController token:" +  token);
            //指定key
            String hashKey = key + token;
            //存储token
            stringRedisTemplate.opsForHash().putAll(hashKey,map);
            //设置过期时间
            stringRedisTemplate.expire(hashKey,20, TimeUnit.MINUTES);

            ro.setCode(0);
            ro.setMsg("登录成功");
            ro.setData(token);
        } else {
            ro.setCode(1);
            ro.setMsg("失败");
            ro.setData("");
        }
        return ro;
    }


    @PostMapping("/app/redis/query")
    public ResultObject query(String accessToken){

        ResultObject ro = new ResultObject();

        String hasKey = key + accessToken;
        if( stringRedisTemplate.hasKey(hasKey) ){
            Map<Object, Object> entry = stringRedisTemplate.opsForHash().entries(hasKey);
            Object userId = entry.get("userId");
            Object role = entry.get("role");
            if("admin".equals((String)role)){
                // 从redis获取token对应的userId数据， 执行userId的数据库查询等等
                ro.setMsg("用户可以执行操作");
                ro.setCode(0);
                ro.setData("");
            }
        }

        return ro;
    }
}